//
//  XXPlaceholderTextView.swift
//  App
//
//  Created by LXF on 2018/9/12.
//Copyright © 2018年 LXF. All rights reserved.
//

import UIKit

public class XXPlaceholderTextView: UITextView {

    public var placeholder:String?{
        didSet{
            self.setNeedsDisplay()
        }
    }
    public var placeholderColor:UIColor?{
        didSet{
            self.setNeedsDisplay()
        }
    }
    
    override public var font: UIFont?{
        didSet{
            self.setNeedsDisplay()
        }
    }
    override public var text: String!{
        didSet{
            self.setNeedsDisplay()
        }
    }
    override public var attributedText: NSAttributedString!{
        didSet{
            self.setNeedsDisplay()
        }
    }

    static func initAndInit()->XXPlaceholderTextView {
        let v = XXPlaceholderTextView.init()
        v.initTextView()
        return v
    }
    
    open func initTextView(){
        //监听文本的输入
        NotificationCenter.default.addObserver(self, selector: #selector(textDidChange), name: UITextView.textDidChangeNotification, object: self)
    }
    
    @objc
    open func textDidChange(){
        setNeedsDisplay()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    public override func draw(_ rect: CGRect) {
        if self.hasText {
            return
        }
        
        guard let pliStr = self.placeholder as NSString? else { return  }
        
        let X:CGFloat = 5
        let Y:CGFloat = 8
        let W:CGFloat = rect.width - (2 * X)
        let H:CGFloat = rect.height - (2 * Y)
        
        var attrtDict:[NSAttributedString.Key : Any] = [:]
        
        attrtDict[NSAttributedString.Key.foregroundColor] = self.placeholderColor ?? UIColor.gray
        attrtDict[NSAttributedString.Key.font] = self.font ?? UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.medium)
        
        pliStr.draw(in: CGRect.init(x: X, y: Y, width: W, height: H), withAttributes: attrtDict)

    }
    
}
